<template>
  <div class="app-page">
    <el-table-form ref="form" class="form" :model="query" label-position="right">
      <el-form-item :table-form-merge="2" label="" label-width="0" class="merge-item">
        <el-select v-model="query.type" style="width: 170px; margin-right: 2px;">
          <el-option label="签收日期" value="signTime" />
          <el-option label="下单日期" value="transactTime" />
        </el-select>
        <el-date-picker
          v-model="query.date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :clearable="false"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>
      <el-form-item label="所属机构:">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
          @select-clear="closeTree"
        />
      </el-form-item>
      <el-form-item v-if="mode === 1" label="归属人:">
        <el-select v-model="query.ownerId" clearable placeholder="请选择">
          <el-option
            v-for="l in userData"
            :key="l.userId"
            :value="l.userId"
            :label="l.userName"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="mode === 2" label="客户编号:" class="merge-item">
        <el-input v-model.trim.trim="query.csmCode" clearable placeholder="请输入" />
      </el-form-item>
      <el-form-item v-if="mode === 2" label="客户名称:" class="merge-item">
        <el-input v-model.trim="query.csmName" clearable placeholder="请输入" />
      </el-form-item>
      <el-form-item v-if="mode === 2" label="客户电话:" class="merge-item">
        <el-input v-model.trim="query.contactPhone" clearable placeholder="请输入" />
      </el-form-item>
      <template v-slot:btns>
        <el-button
          v-permission="1"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button
          v-permission="4"
          :loading="$loadingPlugin.exportFile"
          type="primary"
          icon="el-icon-download"
          @click="exportFile"
        >导出</el-button>
      </div>
      <div>
        <el-link
          v-permission="2"
          style="font-size: 16px; color: #126edc;"
          class="btn"
          size="mini"
          :underline="false"
          @click="modeChange"
        >
          <i style="transform: rotate(-90deg);" class="el-icon-sort" />&nbsp;{{
            mode === 1 ? "客户模式" : "配送员模式"
          }}</el-link>
        <!-- <el-select v-model="mode" style="width: 150px;" @change="modeChange">
          <el-option :value="1" label="配送员模式" />
          <el-option :value="2" label="客户模式" />
        </el-select> -->
      </div>
    </div>
    <lb-table
      v-if="mode === 1"
      ref="lbTable"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      v-loading="$loadingPlugin.fetchData"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <lb-table
      v-if="mode === 2"
      ref="lbTable"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      v-loading="$loadingPlugin.fetchData"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <dispose
      ref="dispose"
      :payment-method-map="PaymentMethodMap"
      :pay-status-map="PayStatusMap"
      @refresh="refresh"
    />
    <detail ref="detail" />
  </div>
</template>

<script>
  import getTreeData from '@/utils/jsonTree'
  // import tableData from './data.json'
  import { mapGetters } from 'vuex'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import {
    orderbillNewReceiptList,
    queryMap,
    batchUserOrder,
    newReceiptExport,
    queryExportDomain
  } from '@/api'
  import moment from 'dayjs'
  export default {
    name: 'orderReceipt',
    components: {
      dispose: require('./components/dispose.vue').default,
      detail: require('./components/detail.vue').default
    },
    data() {
      return {
        treeData: [],
        searchParams: {
          mode: 1,
          type: 'signTime'
        },
        mode: 1,
        searchMode: 1,
        searchType: 'signTime',
        PaymentMethodMap: [],
        PayStatusMap: [],
        userData: [], // 处理人
        query: {
          type: 'signTime',
          date: [moment().startOf('month').format('YYYY-MM-DD'), moment().endOf('day').format('YYYY-MM-DD')],
          orgSNNo: '',
          csmCode: null,
          csmName: null,
          contactPhone: null
        },
        tableData: {
          //     	{title: '处理人/配送员', field: 'ownerName', width: 200, align: 'center'},
          // {title: '客户名称', field: 'csmName', width: 200, align: 'center'},
          // {title: '未签收未回执', field: 'noSignNoReceiptCount', width: 200, align: 'center',formatter:this.formatter.noSignWindowFormat1},
          // {title: '未签收应收金额', field: 'noSignTReceivablesCount', width: 200, align: 'center',formatter:this.formatter.noSignWindowFormat2},
          // {title: '已签收未回执', field: 'signNoReceiptCount', width: 200, align: 'center',formatter:this.formatter.signWindowFormat1},
          // {title: '签收未回执应收金额', field: 'signNoReceiptTReceivablesCount', width: 300, align: 'center',formatter:this.formatter.signWindowFormat2}
          total: 0,
          // column: [
          //   {
          //     prop: 'ownerName',
          //     label: '处理人/配送员',
          //     align: 'center'
          //     // render: (h, { row }) => <el-link onClick={() => this.openDetail(row)}>{row.orderCode}</el-link>
          //   },
          //   { label: '未签收未回执', prop: 'noSignNoReceiptCount', width: 200, align: 'center',
          //     render: (h, { row }) => <el-link underline={false} onClick={() => this.openDetail(row)}>{row.noSignNoReceiptCount}</el-link>
          //   },
          //   { label: '未签收应收金额', prop: 'noSignTReceivablesCount', width: 200, align: 'center',
          //     render: (h, { row }) => <el-link underline={false} onClick={() => this.openDetail(row)}>{row.noSignTReceivablesCount}</el-link>
          //   },
          //   {
          //     prop: 'signNoReceiptCount',
          //     label: '已签收未回执',
          //     align: 'center',
          //     showOverflowTooltip: true,
          //     render: (h, { row }) => <el-link underline={false} onClick={() => this.openDispose(row)}>{row.signNoReceiptCount}</el-link>

          //   },
          //   {
          //     prop: 'signNoReceiptTReceivablesCount',
          //     label: '签收未回执应收金额',
          //     align: 'center',
          //     render: (h, { row }) => <el-link underline={false} onClick={() => this.openDispose(row)}>{row.signNoReceiptTReceivablesCount}</el-link>
          //   }

          // ],
          data: []
        },
        tableDataForUsers: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters(['orgList']),
      column() {
        const column = [
          {
            type: 'index',
            align: 'center'
          },
          {
            prop: this.searchMode === 1 ? 'ownerName' : 'csmName',
            label: this.searchMode === 1 ? '处理人/配送员' : '客户名称'
          },
          {
            label: '未签收未回执',
            prop: 'noSignNoReceiptCount',
            width: 200,
            align: 'right'
            // render: (h, { row }) => (
            //   row.noSignNoReceiptCount && row.noSignNoReceiptCount !== 0 ? <el-link underline={false} onClick={() => this.openDetail(row)}>
            //   {row.noSignNoReceiptCount}
            // </el-link> : <span>{ row.noSignNoReceiptCount }</span>
            // )
          },
          {
            label: '未签收应收金额',
            prop: 'noSignTReceivablesCount',
            width: 200,
            align: 'right'
            // render: (h, { row }) => (
            //   row.noSignTReceivablesCount && row.noSignTReceivablesCount !== 0 ? <el-link underline={false} onClick={() => this.openDetail(row)}>
            //   {row.noSignTReceivablesCount}
            // </el-link> : <span>{ row.noSignTReceivablesCount }</span>
            // )
          },
          {
            prop: 'signNoReceiptCount',
            label: '已签收未回执',
            align: 'right',
            showOverflowTooltip: true
            // render: (h, { row }) => (
            //   row.signNoReceiptCount && row.signNoReceiptCount !== 0 ? <el-link underline={false} onClick={() => this.openDispose(row)}>
            //   {row.signNoReceiptCount}
            // </el-link> : <span>{ row.signNoReceiptCount }</span>
            // )
          },
          {
            prop: 'signNoReceiptTReceivablesCount',
            label: '签收未回执应收金额',
            align: 'right'
            // render: (h, { row }) => (
            //   row.signNoReceiptTReceivablesCount && row.signNoReceiptTReceivablesCount !== 0 ? <el-link underline={false} onClick={() => this.openDispose(row)}>
            //   {row.signNoReceiptTReceivablesCount}
            // </el-link> : <span>{ row.signNoReceiptTReceivablesCount }</span>
            // )
          },
          {
            label: '操作',
            fixed: 'right',
            width: 100,
            render: (h, { row, $index }) => {
              return (
                <el-link v-permission='3' underline={false} onClick={() => this.openDispose(row)}>回执确认</el-link>
              )
            }
          }
        ]
        if (this.searchType === 'signTime') {
          column.splice(2, 2)
          return column
        }
        return column
      }
    },
    async created() {
      // console.log(this.organization)
      this.getExportDomain()
      this.getTreeData()
      this.getPayStatus()
    },
    methods: {
      // 模式改变
      modeChange() {
        if (this.mode === 1) {
          this.mode = 2// 客户模式
          this.fetchData({})
        } else if (this.mode === 2) {
          this.mode = 1
          this.fetchData({}) // 配送员模式
        }
      },
      async fetchData({ currentPage = 1, pageSize = 20 }) {
        const params = {
          currentPage,
          pageSize,
          orgSNNo: this.query.orgSNNo,
          ownerId: this.query.ownerId,
          csmCode: this.query.csmCode,
          csmName: this.query.csmName,
          contactPhone: this.query.contactPhone,
          type: this.mode + ''
        }
        if (this.query.date) {
          params[this.query.type] = this.query.date[0] + ' ' + '00:00:00'
          params[`${this.query.type}End`] = this.query.date[1] + ' ' + '23:59:59'
          const diff = moment(this.query.date[1]).diff(moment(this.query.date[0]), 'days')
          if (diff > 93) {
            this.$message.error('选择时间条件相差不能超过3个月')
            return
          }
        }
        const res = await orderbillNewReceiptList(params)
        this.tableData.data = res.data.rows
        this.searchParams = params
        this.searchType = this.query.type
        this.searchMode = this.mode
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      refresh() {
        this.search()
      },
      // 搜索
      search() {
        this.fetchData({})
      },
      // 机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
        this.query.orgSNNo = this.treeData[0].orgSNNo
        this.getOwnersList(this.treeData[0].orgSNNo)
      },
      async selectTreeChange(value) {
        this.query.orgSNNo = value.orgSNNo
        if (this.mode === 1) {
          this.$set(this.query, 'ownerId', '')
          this.getOwnersList(value.orgSNNo)
        }
      },
      // 查询归属人列表
      async getOwnersList(orgSNNo) {
        const res = await batchUserOrder({
          orgSNNo: orgSNNo || ''
        })
        this.userData = res.data
      },
      closeTree() {
        this.$set(this.query, 'ownerId', '')
        this.userData = []
      },
      openDispose(row) {
        var params = {}
        if (this.mode === 1) {
          params = {
            ...this.searchParams,
            ownerId: row.ownerId,
            orderStatus: 10
          }
        }
        if (this.mode === 2) {
          params = {
            ...this.searchParams,
            csmId: row.csmId,
            orderStatus: 10
          }
        }

        this.$refs.dispose.open(params)
      },
      openDetail(row) {
        var params = {}
        if (this.mode === 1) {
          params = {
            ...this.searchParams,
            ownerId: row.ownerId,
            orderStatus: 0
          }
        }
        if (this.mode === 2) {
          params = {
            ...this.searchParams,
            csmId: row.csmId,
            orderStatus: 0
          }
        }
        this.$refs.detail.open(params)
      },
      async getPayStatus() {
        const res1 = await queryMap({ enumName: 'PaymentMethod' })
        const res2 = await queryMap({ enumName: 'PayStatus' })
        this.PaymentMethodMap = res1.data
        this.PayStatusMap = res2.data
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain).then((res) => {
          this.exportDomain = res.data
        })
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      // 导出
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach((item) => {
            str[item.prop] = item.label
          })
          const params = this.searchParams
          if (this.date && this.date.length === 2) {
            params[this.dateType] = this.date[0]
            params[`${this.dateType}End`] = this.date[1]
          }
          newReceiptExport({
            paramInfo: _this._getQuery(params),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      }
    }
  }
</script>

<style scoped lang="scss">
.app-page {
  /deep/ .el-table .el-table__cell .el-link {
    margin-right: 0;
  }
}
.formGroup {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
</style>
